<template>
  <div class="chart-container">
    <div class="Realtime" id="VoltageChart"></div>
    <div class="Realtime" id="CurrentChart"></div>
    <div class="Realtime" id="PowerChart"></div>
    <div class="Realtime" id="PowerFactorChart"></div>
    <div class="Realtime" id="TemperatureChart"></div>
    <div class="Realtime" id="EnergyConsumptionChart"></div>
  </div>
</template>

<script setup>
import { deviceDataService } from "@/services";
import { inject, onMounted, reactive, onUnmounted } from "vue";
import { defineProps } from 'vue';

const $echarts = inject("echarts");
const props = defineProps(['deviceId']);
const data = reactive({
  timestamp: [],
  voltageData: [],
  currentData: [],
  powerData: [],
  powerFactorData: [],
  temperatureData: [],
  energyConsumptionTimestamp: [],
  energyConsumptionData: [],
});
const charts = {};

onMounted(async () => {
  await fetchData();
  initCharts();
  window.addEventListener("resize", resizeCharts);
});

onUnmounted(() => {
  window.removeEventListener("resize", resizeCharts);
  disposeCharts();
});

async function fetchData() {
  try {
    const response = await deviceDataService.getDayDataService(props.deviceId);
    const { ele_data, ele_quantity } = response.data.time_series_data[props.deviceId];
    console.log('response.data.time_series_data[props.deviceId]', response.data.time_series_data[props.deviceId])
    setData(ele_data, ele_quantity);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

function setData(eleData, eleQuantity) {
  data.timestamp = eleData.map((v) => v.timestamp.split(" ")[1]).reverse();
  data.voltageData = eleData.map((v) => v.voltage).reverse();
  data.currentData = eleData.map((v) => v.current / 1000).reverse();
  data.powerData = eleData.map((v) => v.active_power).reverse();
  data.powerFactorData = eleData.map((v) => parseFloat(v.power_factor)).reverse();
  data.temperatureData = eleData.map((v) => v.temperature).reverse();
  data.energyConsumptionTimestamp = eleQuantity.map((v) => v.timestamp.split(" ")[1]).reverse();
  data.energyConsumptionData = eleQuantity.map((v) => v.data / 1000).reverse();
  console.log("data.energyConsumptionData", data.energyConsumptionData)
}

function initCharts() {
  const colors = [
    { start: "rgba(0, 255, 255, 0.5)", end: "rgba(0, 255, 255, 0.1)", line: "rgba(0, 255, 255, 1)" },
    { start: "rgba(0, 255, 0, 0.5)", end: "rgba(0, 255, 0, 0.1)", line: "rgba(0, 255, 0, 1)" },
    { start: "rgba(255, 0, 0, 0.5)", end: "rgba(255, 0, 0, 0.1)", line: "rgba(255, 0, 0, 1)" },
    { start: "rgba(255, 255, 0, 0.5)", end: "rgba(255, 255, 0, 0.1)", line: "rgba(255, 255, 0, 1)" },
    { start: "rgba(0, 0, 255, 0.5)", end: "rgba(0, 0, 255, 0.1)", line: "rgba(0, 0, 255, 1)" },
    { start: "rgba(128, 0, 128, 0.5)", end: "rgba(128, 0, 128, 0.1)", line: "rgba(128, 0, 128, 1)" },
  ];

  initChart("VoltageChart", "电压", [{ name: "电压", data: data.voltageData }], colors.slice(0, 1), 'V');
  initChart("CurrentChart", "电流", [{ name: "电流", data: data.currentData }], colors.slice(1, 2), 'A');
  initChart("PowerChart", "功率", [{ name: "功率", data: data.powerData }], colors.slice(2, 3), 'W');
  initChart("PowerFactorChart", "功率因数", [{ name: "功率因数", data: data.powerFactorData }], colors.slice(3, 4), '%');
  initChart("TemperatureChart", "温度", [{ name: "温度", data: data.temperatureData }], colors.slice(4, 5), '℃');
  initEnergyChart("EnergyConsumptionChart", "用电量", [{ name: "用电量", data: data.energyConsumptionData }], colors.slice(5, 6), '度');
}

function initChart(chartId, title, seriesData, color, unit) {
  const chartElement = document.getElementById(chartId);
  if (!chartElement) return;
  let myChart = $echarts.init(chartElement);

  myChart.setOption({
    title: {
      text: title,
      left: "center",
      textStyle: {
        fontSize: 18,
        fontWeight: "bold",
        color: "#00FFFF",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
      backgroundColor: "rgba(0, 0, 0, 0.7)",
      borderColor: "#fff",
      borderWidth: 1,
      textStyle: {
        color: "#fff",
      },
      formatter: function (params) {
        let result = params[0].name + '<br/>';
        params.forEach(item => {
          result += item.marker + item.seriesName + ': ' + item.value + (unit ? ' ' + unit : '') + '<br/>';
        });
        return result;
      }
    },
    legend: {
      data: seriesData.map((item) => item.name),
      top: "10%",
      textStyle: {
        fontSize: 14,
        color: "#00FFFF",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: data.timestamp.map(time => time.substring(0, 5)), // 只保留时分部分
      axisLabel: {
        color: "#00FFFF",
      },
      axisLine: {
        lineStyle: {
          color: "#333",
        },
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: '{value}' + (unit ? ' ' + unit : ''),
        color: "#00FFFF",
      },
      axisLine: {
        lineStyle: {
          color: "#333",
        },
      },
      splitLine: {
        lineStyle: {
          color: "rgba(255, 255, 255, 0.1)",
        },
      },
    },
    series: seriesData.map((item, index) => ({
      name: item.name,
      data: item.data,
      type: "line",
      smooth: true,
      showSymbol: false,
      areaStyle: {
        opacity: 0.3,
        color: new $echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: color[index].start },
          { offset: 1, color: color[index].end },
        ]),
      },
      lineStyle: {
        width: 2,
        color: color[index].line,
      },
    })),
  });

  charts[chartId] = myChart;
}

function initEnergyChart(chartId, title, seriesData, color, unit) {
  const chartElement = document.getElementById(chartId);
  if (!chartElement) return;
  let myChart = $echarts.init(chartElement);

  myChart.setOption({
    title: {
      text: title,
      left: "center",
      textStyle: {
        fontSize: 18,
        fontWeight: "bold",
        color: "#00FFFF",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
      backgroundColor: "rgba(0, 0, 0, 0.7)",
      borderColor: "#fff",
      borderWidth: 1,
      textStyle: {
        color: "#fff",
      },
      formatter: function (params) {
        let result = params[0].name + '<br/>';
        params.forEach(item => {
          result += item.marker + item.seriesName + ': ' + item.value + (unit ? ' ' + unit : '') + '<br/>';
        });
        return result;
      }
    },
    legend: {
      data: seriesData.map((item) => item.name),
      top: "10%",
      textStyle: {
        fontSize: 14,
        color: "#00FFFF",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: data.energyConsumptionTimestamp.map(time => time.substring(0, 5)), // 只保留时分部分
      axisLabel: {
        color: "#00FFFF",
      },
      axisLine: {
        lineStyle: {
          color: "#333",
        },
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: '{value}' + (unit ? ' ' + unit : ''),
        color: "#00FFFF",
      },
      axisLine: {
        lineStyle: {
          color: "#333",
        },
      },
      splitLine: {
        lineStyle: {
          color: "rgba(255, 255, 255, 0.1)",
        },
      },
    },
    series: seriesData.map((item, index) => ({
      name: item.name,
      data: item.data,
      type: "line",
      smooth: true,
      showSymbol: false,
      areaStyle: {
        opacity: 0.3,
        color: new $echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: color[index].start },
          { offset: 1, color: color[index].end },
        ]),
      },
      lineStyle: {
        width: 2,
        color: color[index].line,
      },
    })),
  });

  charts[chartId] = myChart;
}

function resizeCharts() {
  for (let chart in charts) {
    if (charts[chart]) {
      charts[chart].resize();
    }
  }
}

function disposeCharts() {
  for (let chart in charts) {
    if (charts[chart]) {
      charts[chart].dispose();
      charts[chart] = null;
    }
  }
}
</script>

<style scoped>
.chart-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 10px;
}

.Realtime {
  top: 50px;
  width: 48%;
  height: 250px;
  /* 增加高度以填充纵向位置 */
}
</style>
